import os
import cv2
import copy

import numpy as np

import utils
import random
from tqdm import tqdm


SrcPath = r'J:\Temp\1200_300\big'
DstPath = r'J:\Temp\800x300\B'
SrcW = 1200
DstW = 800

NameNum = 0
for root, dirs, files in os.walk(SrcPath):
    for file in tqdm(files):
        if file[-3:] == 'xml':
            infos = utils.ReadXml(root + '\\' + file)
            img = cv2.imread(root + '\\' + file[:-3] + 'jpg')
            for i in range(len(infos) - 1):
                for j in range(i + 1, len(infos)):
                    if infos[i][0] > infos[j][0]:
                        temp = infos[i]
                        infos[i] = infos[j]
                        infos[j] = temp
            infos_cp = copy.deepcopy(infos)
            W = SrcW
            while W != DstW:
                i = random.randint(-1, len(infos) - 1)
                if i == -1:
                    dx = infos[0][0]
                elif i == len(infos) - 1:
                    dx = W - infos[-1][2]
                else:
                    dx = infos[i + 1][0] - infos[i][2]
                if W - DstW < dx:
                    dw = W - DstW
                elif dx <= 1:
                    continue
                else:
                    dw = random.randint(int(dx / 2), dx - 1)
                W -= dw
                for j in range(i + 1, len(infos)):
                    infos[j][0] -= dw
                    infos[j][2] -= dw
            NewImg = np.zeros((img.shape[0], DstW, 3), dtype=np.uint8)
            for i in range(len(infos)):
                if i == 0:
                    NewImg[:, :infos[0][2]] = img[:, infos_cp[0][2] - infos[0][2]:infos_cp[0][2]]
                else:
                    NewImg[:, infos[i - 1][2]:infos[i][2]] = img[:, infos_cp[i][2] - (infos[i][2] - infos[i - 1][2]):infos_cp[i][2]]
            NameNum += 1
            NewInfos = [DstPath + '\\%05d.xml' % NameNum]
            for info in infos:
                NewInfos.append(info)
            utils.WriteXml(NewInfos, NewImg.shape[1], NewImg.shape[0])
            cv2.imwrite(NewInfos[0][:-3] + 'jpg', NewImg)